package routes

import (
	"mumu_stock_trad/controller"
	"mumu_stock_trad/proxy"
	"net"
	"net/http"

	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

var whitelistIP = []string{
	"172.31.0.0/24",
	"127.0.0.1",
}

func ipWhiteList() gin.HandlerFunc {
	if viper.GetString("ctl_ip_whitelist") == "true" {
		return func(c *gin.Context) {
			clientIp := c.ClientIP()
			ip := net.ParseIP(clientIp)

			found := false
			for _, network := range whitelistIP {
				// Firstly check whether this is a CIDR
				_, subnet, _ := net.ParseCIDR(network)
				if subnet != nil && subnet.Contains(ip) {
					found = true
					break
				} else if subnet == nil && clientIp == network {
					// This is not a CIDR, but a simple IP (mostly from external access), now check whether they are identical
					found = true
					break
				}
			}
			if !found {
				log.Error("Source IP: ", clientIp, " forbidden")
				c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
					"status":       http.StatusForbidden,
					"errorCode":    -1,
					"errorMessage": "Permission denied",
					"data":         nil,
				})
				return
			}
		}
	} else {
		return func(c *gin.Context) {}
	}
}

func loadAPI(api *gin.RouterGroup, hub *proxy.Hub) {
	apis := api.Group("/api")
	{
		/*  内部接口 */
		// apis.GET("/all", ipWhiteList(), func(c *gin.Context) {
		// 	controller.GetAllCategories(c)
		// })

		apis.GET("/stock/:symbol", controller.GetStockData)        // http://localhost:9527/decs-mst/api/stock/1
		apis.GET("/stock-qt/:symbol", controller.GetStockDataQt)   // http://localhost:9527/decs-mst/api/stock-qt/1
		apis.GET("/stock-list/:page", controller.GetStockDataList) // http://localhost:9527/decs-mst/api/stock-list/1
		apis.GET("/category", controller.GetCategory)              // http://localhost:9527/decs-mst/api/category
		apis.GET("/category-list", controller.GetAllCategories)    // http://localhost:9527/decs-mst/api/category-list
		apis.GET("/stock-qt-all", controller.GetStockQtAll)        // http://localhost:9527/decs-mst/api/stock-qt-all
		apis.POST("/list", controller.GetList)                     // http://localhost:9527/decs-mst/api/list
		apis.POST("/detail", controller.GetDetail)                 // http://localhost:9527/decs-mst/api/detail
		apis.POST("/add-favorite", controller.AddFavorite)         // http://localhost:9527/decs-mst/api/add-favorite
		apis.POST("/delete-favorite", controller.DeleteFavorite)   // http://localhost:9527/decs-mst/api/delete-favorite
		apis.GET("/stock-sapi", controller.StockSApi)              // http://localhost:9527/decs-mst/api/stock-sapi

	}
}
